
package com.xebest.web.controller.order;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xebest.api.dto.OrderInfoDTO;
import com.xebest.api.dto.OrderInfoDetailDTO;
import com.xebest.api.dto.resdto.OrderInfoResDTO;
import com.xebest.api.service.ForErpOrderIApiService;
import com.xebest.common.base.controller.BaseController;
import com.xebest.common.base.controller.BaseResponse;
import com.xebest.common.enums.erp.order.VenOrderStatusEnum;
import com.xebest.common.enums.erp.storehouse.VenStoreTmsStatusEnum;
import com.xebest.common.enums.logtype.ErpLogTypeEnum;
import com.xebest.common.util.XeBaseUtil;
import com.xebest.config.SendGoodOrderSender;
import com.xebest.util.SysSetBeanUtils;
import com.xebest.util.XeVenBusConstans;
import com.xebest.util.msg.XeVenOrderMsg;
import com.xebest.web.form.XeVenOrderForm;
import com.xebest.web.form.XeVenOrderFromVo;
import com.xebest.web.model.XeVenExpHandleEntity;
import com.xebest.web.service.XeVenExpHandleService;
import com.xebest.web.service.XeVenOrderService;
import com.xebest.web.service.XeVenSendGoodsService;
import com.xebest.web.view.ErpUserInfo;
import com.xebest.web.view.XeVenSendView;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.*;

/**
 * 鲜易云ERP订单发货业务
 *
 * @author 李贝贝
 */
@RestController
@RequestMapping("send")
public class XeVenSendGoodsController extends BaseController {

    private static final Logger log = LoggerFactory.getLogger(XeVenSendGoodsController.class);//日志记录类

    @Autowired
    private XeVenSendGoodsService xeVenSendGoodsService;//发货业务处理

    @Autowired
    private ForErpOrderIApiService forErpOrderIApiService; //发货订单同步业务

    @Autowired
    private XeVenOrderService xeVenOrderService;//订单业务

    @Autowired
    private XeVenExpHandleService xeVenExpHandleService;//异常补偿业务

    /**
     * 鲜易云ERP单个或者多个订单发货
     *
     * @author 李贝贝
     */
    @RequestMapping("batchSend")
    public @ResponseBody
    BaseResponse batchSend(@RequestBody XeVenOrderFromVo form) {
        //1、验证参数

        //2、获取前台需要传入订单号
        List<String> orderIds = new ArrayList<String>();//待发货订单容器
        for (XeVenOrderForm orderForm : form.getXeVenOrderForm()) {
            orderIds.add(orderForm.getOrderId());//订单号
        }
        log.info("订单发货入参：{}", JSONObject.toJSONString(orderIds));
        //3、获取用户登录信息
        ErpUserInfo userInfo = SysSetBeanUtils.getErpUserInfo(super.getErpLoginUserInfo());
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("userCode", userInfo.getUserCode());//商户编码
        //paramMap.put("userCode", "SH1709221914147");//商户编码
        paramMap.put("orderIds", orderIds);//待发货订单号
        //4、批量查询要处理的待发货订单
        List<XeVenSendView> waitSendList = xeVenSendGoodsService.queryWaitSendList(paramMap);
        log.info("批量查询要处理的待发货订单:{}", JSONObject.toJSONString(waitSendList));
        Map<String, Object> map = new HashMap<String, Object>();
        map.put(XeVenBusConstans.CODE, XeVenBusConstans.BUSSINESS_SUCCESS);
        String failOrder = "";//发货失败订单号
        String tmsOrder = "";//接入TMS订单号
        String illegalOrder = "";//非法状态订单号
        String resultMsg = "";//发货返回提示信息
        int sendSize = 0;
        List<XeVenSendView> waitUpList = new ArrayList<XeVenSendView>();
        //5、开始执行批量发货操作
        for (int i = 0; i < waitSendList.size(); i++) {
            XeVenSendView sendView = waitSendList.get(i);
            //判断发货状态是否为待发货 是否已经接入TMS
            if (VenStoreTmsStatusEnum.YES.getValue() == sendView.getTmsStatus()) {
                //记录出执行失败订单号
                tmsOrder += " " + sendView.getOrderId();
                continue;
            }
            if (VenOrderStatusEnum.WAIT_SEND.getValue() != sendView.getOrderStatus()) {
                //记录出执行失败订单号
                illegalOrder += " " + sendView.getOrderId();
                continue;
            }
            sendView.setCreaterUser(userInfo.getLoginName());//创建人
            sendView.setModfiyUser(userInfo.getLoginName());//修改人
            sendView.setSendTime(new Date());
            try {
                int sendResult = xeVenSendGoodsService.updateSend(sendView);//更新发货
                if (sendResult > 0) {
                    waitUpList.add(sendView);//添加待更新发货(商城订单使用)
                    //添加日志
                    xeVenOrderService.insertMqLog(ErpLogTypeEnum.erpOrderModifySend.getValue(), sendView.getOrderId(), "对订单【" + sendView.getOrderId() + "】进行发货操作", userInfo, getRequestIP(), "发货");
                }
                sendSize += sendResult;
            } catch (Exception e) {
                failOrder += " " + sendView.getOrderId();
                log.error("订单发货错误信息:订单号{},发货执行异常{}!", sendView.getOrderId(), e);
            }
        }
        //6、批量发货提示信息拼接
        if (!tmsOrder.equals("")) {
            tmsOrder += XeVenOrderMsg.SEND_TMSMSG;
            resultMsg = " 失败原因：订单号" + tmsOrder;
        }
        if (!illegalOrder.equals("")) {
            illegalOrder += XeVenOrderMsg.SEND_ILLEGALMSG;
            resultMsg = " 失败原因：订单号" + illegalOrder;
        }
        if (!failOrder.equals("")) {
            failOrder += XeVenOrderMsg.SEND_FAIL_MSG;
            resultMsg = " 订单号" + failOrder;
        }
        map.put(XeVenBusConstans.MSG, "成功发货" + sendSize + "条！" + resultMsg);
        //7、通知商城订单库已发货，同时算三方商户佣金
        int waitUpListSize = waitUpList.size();//需要通知的订单数量
        List<String> expOrderList = new ArrayList<String>();//如果发货通知异常使用
        try {
            if (waitUpListSize > 0) {
                List<OrderInfoDTO> listDTO = new ArrayList<OrderInfoDTO>();
                OrderInfoDTO paramDTO = new OrderInfoDTO();//商城同步参数
                for (XeVenSendView viewDTO : waitUpList) {
                    expOrderList.add(viewDTO.getOrderId());
                    OrderInfoDTO orderInfoDTO = new OrderInfoDTO();
                    orderInfoDTO.setVenType(viewDTO.getVenType());
                    orderInfoDTO.setOrderId(viewDTO.getOrderId());
                    orderInfoDTO.setSendTime(viewDTO.getSendTime());
                    orderInfoDTO.setOrderStatus(VenOrderStatusEnum.SEND.getValue());
                    orderInfoDTO.setUserCode(viewDTO.getUserCode());
                    orderInfoDTO.setOrderDetailList(JSON.parseArray(JSON.toJSONString(viewDTO.getOrderDetailList()), OrderInfoDetailDTO.class));
                    orderInfoDTO.setPayAmount(viewDTO.getEpayReceAmt() == null ? viewDTO.getPayAmount() : viewDTO.getEpayReceAmt());//应收金额
                    orderInfoDTO.setRealRefundedAmount(viewDTO.getDifferAmount());//退款总额
                    int i = 0;
                    for (OrderInfoDetailDTO detailDTO : orderInfoDTO.getOrderDetailList()) {
                        BigDecimal refundAmount = viewDTO.getOrderDetailList().get(i).getDifferenceAmount();
                        //v3.1.4 平台优惠金额 佣金计算需要加上 如果有实发，则根据实发数 计算平台优惠金额   商品明细 优惠=(优惠)*拆分数量/购买数量
                        BigDecimal platCpn = XeBaseUtil.baseUtil.calPlatCpnAmt(detailDTO.getPurchaseNum(), detailDTO.getRealSendNum(), detailDTO.getPlatPmtAmount());
                        BigDecimal sendAmt = XeBaseUtil.baseUtil.calSendAmt(detailDTO.getPurchaseNum(), detailDTO.getRealSendNum(), detailDTO.getProTotalPrice(), detailDTO.getPmtAmount());
                        log.info("商品sku{}，平台优惠券金额{}，发货金额{}", detailDTO.getProSku(), platCpn, sendAmt);
                        detailDTO.setProPayAmount(sendAmt);
                        detailDTO.setPlatPmtAmount(platCpn);
                        if (refundAmount != null) {
                            // detailDTO.setProPayAmount(detailDTO.getProPayAmount().subtract(refundAmount));//发货金额 = 成交金额-差异退款金额 不算运费
                            detailDTO.setRealRefundedAmount(refundAmount);//退款金额
                        } else {
                            detailDTO.setRealRefundedAmount(new BigDecimal("0.00"));//退款金额
                        }
                        i++;
                    }
                    listDTO.add(orderInfoDTO);
                }
                paramDTO.setOrderInfoList(listDTO);
                log.info("发货通知前台入参 :{}", JSON.toJSONString(paramDTO));
                OrderInfoResDTO orderInfoResDTO = this.forErpOrderIApiService.erpConfirmOrder(paramDTO);
                log.info("发货通知前台出参 :{}", JSON.toJSONString(orderInfoResDTO));
                if (!orderInfoResDTO.getStatus().equals("2000")) {
                    XeVenExpHandleEntity entity = new XeVenExpHandleEntity();
                    entity.setExpType(2);
                    entity.setOrderJson(JSONObject.toJSONString(expOrderList));
                    entity.setExpMsg("正常发货通知异常：" + orderInfoResDTO.getMsg());
                    xeVenExpHandleService.insertXeVenExpHandle(entity);
                }
            }
        } catch (Exception e) {
            try {
                XeVenExpHandleEntity entity = new XeVenExpHandleEntity();
                entity.setExpType(2);
                entity.setOrderJson(JSONObject.toJSONString(expOrderList));
                entity.setExpMsg("正常发货通知异常：" + e.getMessage());
                xeVenExpHandleService.insertXeVenExpHandle(entity);
            } catch (Exception e1) {
                log.error("发货通知补偿业务执行异常{}!", e1);
            }
            log.error("订单发货通知前台错误信息:同步发货执行异常{}!", e);
        }
        //发送短信通知
        if (waitUpListSize > 0) {
            SendGoodOrderSender.sender.sendMessage(JSONObject.toJSONString(waitUpList));//消息通知
            log.info("发货通知消息成功!");
        }
        //8、返回结果
        return sendAjaxOK(map);
    }

}
  
